11. Exercise: Conditional Navigation

L3 15 Conditional Navigation SC

You’ll conditionally navigate to a different fragment based upon whether the player answers all of the questions correctly or not.

1. Add the GameWonFragment and GameOverFragment to the navigation graph.

Create actions connecting the GameFragment to the GameWonFragment and GameOverFragment. Move to the GameFragment Kotlin file.

2. Navigate from the gameFragment to the gameWonFragment under the “We’ve won!” comment

Under the “We’ve won!” comment, find the nav controller from the view, and then navigate to the action. To do this, call view.findNavController().navigate( R.id.action_gameFragment_to_gameWonFragment).

// We've won!  Navigate to the gameWonFragment.
view.findNavController()
   .navigate(R.id.action_gameFragment_to_gameWonFragment)

3. Navigate from the gameFragment to the gameOverFragment under the “GameOver” comment

Under the “GameOver” comment, call

view.findNavController().navigate(R.id.action_gameFragment_to_gameOverFragment)
// Game over! A wrong answer sends us to the gameOverFragment.
view.findNavController().
   navigate(R.id.action_gameFragment_to_gameOverFragment)

Now the game is more functional. When all the questions are answered correctly, the gameWonFragment is displayed. An incorrect answer causes the display of the GameOverFragment.

If you want to start at this step, you can download this exercise code from: Step.03-Exercise-Conditional-Navigation.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here Step.03-Solution-Conditional-Navigation or git diff.

Task Description:

You it's your turn to implement Navigation. Check the steps below as you implement them to complete this exercise.

Task List:

Task Feedback:

Great! Now the user can win and lose the trivia game.

Solution: Step.03-Solution-Conditional-Navigation or git diff